﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace OCR
{
    public partial class Train : Form
    {
        private string sourceDefaultFolder = "";
        private string targetDefaultFolder = "";
        private string mergeDefaultFolder = "";
        private string fileName;
        private string fileNameNoExt;
        private string language;
        private string font;
        private string exp;
        public Train()
        {
            InitializeComponent();
        }

        private void btSource_Click(object sender, EventArgs e)
        {
            if (sourceDefaultFolder != "")
            {
                this.fbdSource.SelectedPath = sourceDefaultFolder;
            }
            if (this.fbdSource.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.tbSourceFolder.Text = this.fbdSource.SelectedPath;
            }
        }

        private void tbTargetFolder_TextChanged(object sender, EventArgs e)
        {

        }

        private void btTarget_Click(object sender, EventArgs e)
        {
            if (targetDefaultFolder != "")
            {
                this.fbdTarget.SelectedPath = targetDefaultFolder;
            }
            if (this.fbdTarget.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.tbTargetFolder.Text = this.fbdTarget.SelectedPath;
            }
        }

        private void btTrans_Click(object sender, EventArgs e)
        {

            DateTime begin = DateTime.Now;
            DirectoryInfo dic = new DirectoryInfo(this.tbSourceFolder.Text);


            foreach (FileInfo file in dic.GetFiles("*.*", SearchOption.TopDirectoryOnly))
            {
                if (file.Extension == ".jpg" || file.Extension == ".bmp")
                {
                    Bitmap pic = new Bitmap(file.FullName);
                    string newFileName = file.Name.Substring(0, file.Name.LastIndexOf('.')) + ".tif";
                    pic.Save(Path.Combine(this.tbTargetFolder.Text, newFileName), System.Drawing.Imaging.ImageFormat.Tiff);
                }
            }
            DateTime end = DateTime.Now;

            TimeSpan ts1 = new TimeSpan(begin.Ticks);
            TimeSpan ts2 = new TimeSpan(end.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();


            this.lbTime.Text = ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + "秒" + ts.Milliseconds.ToString() + "毫秒";
        }
        //打开合并的tif文件
        private void btnMerge_Click(object sender, EventArgs e)
        {

            if (this.ofdMerge.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //文件合路径
                this.tbMerge.Text = this.ofdMerge.FileName;
                //文件所在的文件夹
                this.mergeDefaultFolder = this.tbMerge.Text.Substring(0, this.tbMerge.Text.LastIndexOf('\\'));
                //不带路径文件名
                this.fileName = this.ofdMerge.SafeFileName;
                //不带扩展名的文件名
                this.fileNameNoExt = this.fileName.Substring(0, this.fileName.LastIndexOf('.'));
                string[] abc = this.fileName.Split('.');
                //语言
                this.language = abc[0];
                //字体
                this.font = abc[1];
                if(abc.Length>3)
                {
                    this.exp = abc[2];
                }
                //第二步：生成box文件
                this.tbBox.Text = "tesseract " + this.tbMerge.Text + " " + this.mergeDefaultFolder + "\\" + this.fileNameNoExt + " -l eng -psm 7 batch.nochop makebox";

            }

        }
        //生成盒子文件
        private void btnBox_Click(object sender, EventArgs e)
        {
            string output = "";
            CmdHelper.RunCmd(this.tbBox.Text);
        }



        private void btnBatExe_Click(object sender, EventArgs e)
        {
            Process proc = null;
            try
            {
                proc = new Process();


                proc.StartInfo.FileName = Path.Combine(this.mergeDefaultFolder, "training2.bat");

                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.CreateNoWindow = false;
                //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示，经实践可行
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
        }
        public void writeBATFile(string filePath, string fileContent)
        {

            FileStream fs1 = new FileStream(filePath, FileMode.Create, FileAccess.Write);//创建写入文件
            StreamWriter sw = new StreamWriter(fs1);
            sw.WriteLine(fileContent);//开始写入值
            sw.Close();
            fs1.Close();

        }


        //训练字体,有一定延时
        private void btnTraining_Click(object sender, EventArgs e)
        {
            string comand = @"cd /d " + this.mergeDefaultFolder + @"&&echo {1} 0 0 0 0 0 >font_properties&&tesseract {0}.{1}.{2}.tif {0}.{1}.{2} -l eng -psm 7 nobatch box.train&&unicharset_extractor {0}.{1}.{2}.box&&shapeclustering -F font_properties -U unicharset -O {0}.unicharset {0}.{1}.{2}.tr&&mftraining -F font_properties -U unicharset -O {0}.unicharset {0}.{1}.{2}.tr&&cntraining {0}.{1}.{2}.tr";
            
            comand = string.Format(comand, this.language,this.font,this.exp);
            CmdHelper.RunCmd(comand);
        }
        //合并字体
        private void btnCreate_Click(object sender, EventArgs e)
        {
            while (true)
            {
                if (File.Exists(Path.Combine(this.mergeDefaultFolder, "inttemp")))
                {

                    string comand = @"cd /d " + this.mergeDefaultFolder + @"&&rename normproto {0}.normproto&&rename inttemp {0}.inttemp&&rename pffmtable {0}.pffmtable &&rename unicharset {0}.unicharset&&rename shapetable {0}.shapetable&&combine_tessdata {0}.";
                    comand = string.Format(comand, this.font);
                    CmdHelper.RunCmd(comand);
                    this.tbNewFont.Text = this.mergeDefaultFolder + "\\" + this.font + ".traineddata";
                    //删除中间临时文件

                    DirectoryInfo dic = new DirectoryInfo(this.mergeDefaultFolder);

                    foreach (var item in dic.GetFiles())
                    {
                        if (item.Extension == ".tif" || item.Extension == ".box" || item.Extension == ".traineddata")
                        {

                        }
                        else
                        {
                            item.Delete();
                        }
                    }
                    break;
                }
                else
                {
                    Thread.Sleep(1000);
                    continue;
                }
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(this.mergeDefaultFolder);
        }
        //打开字符矫正程序
        private void btnjTessboxEditor_Click(object sender, EventArgs e)
        {

         System.Diagnostics.Process.Start(@"D:\Lingxin.Card\jTessBoxEditorFX");
        }

        private void Train_Load(object sender, EventArgs e)
        {

        }



    }
}
